package com.randev.snapgallery;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.Gallery;
import android.widget.TextView;
import android.widget.Toast;

import com.randev.snap.MainMenuActivity;
import com.randev.snap.R;
import com.randev.snapconfig.Config;
import com.randev.snapdb.AlbumDetails;

@SuppressWarnings("deprecation")
public class ImageViewActivity extends Activity {

	Gallery gViewImages;
	TextView tViewTitle, tViewDescription, tViewLocation;
	
	String folderName = "", imageName="";
	String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
	String HOME_DIRECTORY = sdCard + File.separator + "AndroidTest";
	boolean EXTERNAL_STORAGE_AVAILABLE = false;
	int currentImage = 0;
	ImageViewAdapter imageViewAdapter;
	private final String TAG = "ImageViewActivity";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.image_view);
		
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		gViewImages = (Gallery) findViewById(R.id.gvImages);
		tViewTitle = (TextView) findViewById(R.id.tvTitle);
		tViewLocation = (TextView) findViewById(R.id.tvLocation);
		tViewDescription = (TextView) findViewById(R.id.tvDescription);
		
		EXTERNAL_STORAGE_AVAILABLE = isExternalStorageWritable();
		getDataFromPreviousActivity();

        
        setImageViewAdapter();
        setAlbumDetails(folderName);
        
        
        try {
        	if (EXTERNAL_STORAGE_AVAILABLE) {
        		File imageFolder = new File(HOME_DIRECTORY + File.separator + folderName);
        		if (imageFolder.exists()) {
        			String[] images = imageFolder.list();
        			boolean imageFound = false;
        			for (int i = 0; i < images.length; i++) {
        				String image = images[i];
        				if (image.contentEquals(imageName)) {
        					imageFound = true;
        					currentImage = i;
        				}
        			}
					if (imageFound) {
						gViewImages.setSelection(currentImage);
					} else {
						Toast.makeText(this, "Image not found!", Toast.LENGTH_SHORT).show();
						currentImage = 0;
					}
        		}
        		
        	} else {
        		AlertDialog.Builder alertDialog = new AlertDialog.Builder(ImageViewActivity.this);
            	alertDialog.setTitle(ImageViewActivity.this.getString(R.string.warning));
            	TextView tViewWarning = new TextView(ImageViewActivity.this);
            	tViewWarning.setGravity(Gravity.CENTER_HORIZONTAL);
            	tViewWarning.setHeight(90);
            	alertDialog.setView(tViewWarning);
            	tViewWarning.setText(ImageViewActivity.this.getString(R.string.sd_card_not_detected));
    		    alertDialog.setPositiveButton(ImageViewActivity.this.getString(R.string.okay), new DialogInterface.OnClickListener() {
    				
    				@Override
    				public void onClick(DialogInterface dialog, int which) {
    					dialog.dismiss();
    					try {
    						Intent MainMenuIntent = new Intent(ImageViewActivity.this, MainMenuActivity.class);
    						finish();
    						startActivity(MainMenuIntent);
    					} catch (ActivityNotFoundException e) {
    						Log.w(TAG, "Error starting camera Activity:" + e.toString());
    					}
    				}
    			});
            	
            	alertDialog.show();        	} 
        } catch (Exception e) {
    		Log.w(TAG, "Error Setting Initial Image: " + e.toString()); 
        }
       
		
	}

	private void getDataFromPreviousActivity() {
		try {
			Bundle extras = getIntent().getExtras();
			folderName = extras.getString(Config.FOLDER_ID);
			imageName = extras.getString(Config.IMAGE_NAME);
		} catch (Exception e) {
			Log.w(TAG, "Unable to get data from previous activity: " + e.toString());
		}
	}
	
	private void setAlbumDetails(String folderName) {
		
		try {
			AlbumDetails albumDetails = new AlbumDetails(this);
			albumDetails.openReadableDatabase();
			ArrayList<String> ad = albumDetails.getAlbumDetailsByAlbumId(folderName);
			albumDetails.closeDatabase();
			
			String location = ad.get(6) + ".";
			String title = ad.get(2);
			String description = ad.get(3) + " <strong>At</strong> ";
			
			tViewTitle.setText(title);
			tViewLocation.setText(location);
			tViewDescription.setText(Html.fromHtml(description));
		} catch (SQLException e) {
			Log.w(TAG, "Error getting data from db: " + e.toString());
		} catch (NullPointerException e) {
			Log.w(TAG, "Error setting album details: " + e.toString());
		} catch (IndexOutOfBoundsException e) {
			Log.w(TAG, "Error setting album details: " + e.toString());		
		}
	}
	
	private boolean isExternalStorageWritable() {
		boolean isMediaAvailable = false;
	    String state = Environment.getExternalStorageState();
	    if (Environment.MEDIA_MOUNTED.equals(state)) {
	    	isMediaAvailable =  true;
	    }
	    return isMediaAvailable;
	}
	
	private void setImageViewAdapter() {
		File imageFolder = new File(HOME_DIRECTORY + File.separator + folderName);
        String[] images = imageFolder.list();
        Log.w("length", images.length + "");
        List<String> imgNameList = Arrays.asList(images);
		imageViewAdapter = new ImageViewAdapter(this, imgNameList, folderName);
		gViewImages.setAdapter(imageViewAdapter);
	}

}